export default class EventEmitter {
  private events!: Map<string, Function[] | undefined>;
  constructor() {
    this.events = new Map();
  }
  // 添加事件监听
  on(eventName: string, listener: Function) {
    if (this.events.get(eventName)) {
      this.events.get(eventName)?.push(listener);
    } else {
      this.events.set(eventName, [listener]);
    }
  }
  // 事件触发
  emit(eventName: string, ...args: any[]) {
    if (this.events.get(eventName)) {
      this.events.get(eventName)?.forEach((fn) => {
        fn.call(this, ...args);
      });
    }
  }
  // 移除事件
  off(eventName: string, listener: Function) {
    if (!this.events.get(eventName)) {
      return;
    }
    this.events.set(
      eventName,
      this.events.get(eventName)?.filter((fn) => fn !== listener)
    );
  }
  // 添加只执行一次的事件
  once(eventName: string, listener: Function) {
    const wrapListener = (...args: any[]) => {
      listener(...args);
      this.off(eventName, wrapListener);
    };
    this.on(eventName, wrapListener);
  }
  has(eventName: string, listener: Function) {
    const handler = this.events.get(eventName);
    return handler?.some((item) => item === listener);
  }
  clear() {
    this.events.clear();
  }
}
